package cn.xuewenbao.ucenter.service.impl;


import cn.xuewenbao.ucenter.entity.Follow;
import cn.xuewenbao.ucenter.entity.MemberData;
import cn.xuewenbao.ucenter.entity.vo.FollowVo;
import cn.xuewenbao.ucenter.mapper.FollowMapper;
import cn.xuewenbao.ucenter.mapper.MemberDataMapper;
import cn.xuewenbao.ucenter.service.FollowService;
import cn.xuewenbao.ucenter.service.MemberDataService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.val;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 关注表 服务实现类
 * </p>
 *
 * @author mafayu
 * @since 2021-04-19
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements FollowService {

    @Autowired
    private FollowMapper followMapper;
    @Autowired
    private MemberDataMapper dataMapper;
    @Autowired
    private MemberDataService dataService;

    @Override
    public Result<Object> getFollowInfo(String userId, String type) {
        Result<Object> result = new Result<>();
        List<FollowVo> followVoList;
        if ("followee".equals(type)) {
            followVoList = followMapper.getFolloweeInfo(userId);
        } else if ("fan".equals(type)) {
            followVoList = followMapper.getFanInfo(userId);
        } else {
            return Result.error("获取的关注type错误");
        }
        result.setSuccess(true);
        result.setResult(followVoList);
        return result;
    }

    @Override
    public Result<?> followOne(String userId, String followedId) {
        //判断是否已关注
        QueryWrapper<Follow> wrapperFollow = new QueryWrapper<>();
        wrapperFollow.eq("user_id", userId).eq("followed_user_id", followedId);
        Follow hasFollow = baseMapper.selectOne(wrapperFollow);
        if (hasFollow != null) {
            return Result.error("当前用户已关注目标用户！");
        }
        //添加关注记录
        Follow follow = new Follow();
        follow.setUserId(userId);
        follow.setFollowedUserId(followedId);
        int update = baseMapper.insert(follow);
        if (update < 1) {
            return Result.error("关注失败");
        }
        //更新关注者的用户数据
        QueryWrapper<MemberData> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        MemberData memberData = dataMapper.selectOne(wrapper);
        if (memberData == null) {
            Boolean addSuccess = dataService.addMemberData(userId, 0L, 0L, 0L, 0L, 1L);
            if (!addSuccess) {
                return Result.error("关注者的用户数据初始化失败");
            }
        } else {
            memberData.setFollowerCount(memberData.getFollowerCount() + 1);
            dataService.updateById(memberData);
        }
        wrapper.clear();
        wrapper.eq("user_id", followedId);
        MemberData memberData2 = dataMapper.selectOne(wrapper);
        if (memberData2 == null) {
            Boolean addSuccess = dataService.addMemberData(followedId, 0L, 0L, 0L, 1L, 0L);
            if (!addSuccess) {
                return Result.error("被关注者的用户数据初始化失败");
            }
        } else {
            memberData2.setFanCount(memberData2.getFanCount() + 1);
            dataService.updateById(memberData2);
        }
        return Result.OK("关注成功", null);
    }

    @Override
    public Result<?> unfollowOne(String userId, String followedId) {
        //删除关注的记录
        QueryWrapper<Follow> wrapperFollow = new QueryWrapper<>();
        wrapperFollow.eq("user_id", userId).eq("followed_user_id", followedId);
        int update = baseMapper.delete(wrapperFollow);
        if (update < 1) {
            return Result.error("关注表中没有该记录");
        }
        //修改关注者的数据
        QueryWrapper<MemberData> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        MemberData memberData = dataMapper.selectOne(wrapper);
        if (memberData == null) {
            return Result.error("用户数据表中未找到关注者");
        }
        if (memberData.getFollowerCount() < 1) {
            return Result.error("关注者的用户数据出错");
        }
        memberData.setFollowerCount(memberData.getFollowerCount() - 1);
        boolean updateSuccess = dataService.updateById(memberData);
        if (!updateSuccess) {
            return Result.error("修改关注着的用户数据出错");
        }
        //修改被关注着的用户数据
        wrapper.clear();
        wrapper.eq("user_id", followedId);
        MemberData memberData2 = dataMapper.selectOne(wrapper);
        if (memberData2 == null) {
            return Result.error("用户数据表中未找到被关注者");
        }
        if (memberData2.getFanCount() < 1) {
            return Result.error("被关注者的用户数据出错");
        }
        memberData2.setFanCount(memberData2.getFanCount() - 1);
        boolean updateSuccess2 = dataService.updateById(memberData2);
        if (!updateSuccess2) {
            return Result.error("修改被关注着的用户数据出错");
        }
        return Result.OK("取关成功", null);
    }

    @Override
    public Result<?> hasFollowOne(String userId, String targetUserId) {
        Result<Boolean> result = new Result<>();
        QueryWrapper<Follow> wrapperFollow = new QueryWrapper<>();
        wrapperFollow.eq("user_id", userId).eq("followed_user_id", targetUserId);
        Follow hasFollow = baseMapper.selectOne(wrapperFollow);
        if (hasFollow == null) {
            result.setSuccess(false);
            result.setMessage("该用户未关注目标用户");
            result.setResult(false);
        } else {
            result.setSuccess(true);
            result.setMessage("已关注");
            result.setResult(true);
        }
        return result;
    }

    //得到该作者的昨天的粉丝量
    @Override
    public Result<Map<String, Long>> getLastFanCount(String userId) {
        Result<Map<String, Long>> result = new Result<>();
        //获取当前日期
        Calendar calendar = Calendar.getInstance();
        //得到前一天
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String lastDay = formatter.format(calendar.getTime());
        String start = "2021-01-01 00:00:00";
        String end = lastDay + " 23:59:59";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        QueryWrapper<Follow> wrapper = new QueryWrapper<>();
        try {
            wrapper.between("gmt_create", sdf.format(sdf.parse(start)), sdf.format(sdf.parse(end)));
            wrapper.eq("followed_user_id", userId);
        } catch (ParseException e) {
            log.error(e.toString());
        }
//        List<Follow> followList = baseMapper.selectList(wrapper);
        final val count = baseMapper.selectCount(wrapper);
        Map<String, Long> map = new HashMap<>();
        map.put(lastDay, Long.valueOf(count));
        result.setResult(map);
        return result;
    }

    //得到该作者的一周的粉丝量
    @Override
    public Result<Map<String, Long>> getWeekFanCount(String userId) {
        Result<Map<String, Long>> result = new Result<>();
        Map<String, Long> map = new HashMap<>();
        //获取当前日期
        Calendar calendar =Calendar.getInstance();
        //得到一周的点赞量
        for (int i = 1;i<= 7;i++){
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String lastDay = formatter.format(calendar.getTime());
            String start = "2021-01-01 00:00:00";
            String end = lastDay + " 23:59:59";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            QueryWrapper<Follow> wrapper = new QueryWrapper<>();
            try {
                wrapper.between("gmt_create", sdf.format(sdf.parse(start)), sdf.format(sdf.parse(end)));
                wrapper.eq("followed_user_id", userId);
            } catch (ParseException e) {
                log.error(e.toString());
            }
            map.put(lastDay, Long.valueOf(baseMapper.selectCount(wrapper)));
        }
        result.setResult(map);
        return result;
    }

    //得到该作者的一月的粉丝量
    @Override
    public Result<Map<String, Long>> getMonthFanCount(String userId) {
        Result<Map<String, Long>> result = new Result<>();
        Map<String, Long> map = new HashMap<>();
        //获取当前日期
        Calendar calendar =Calendar.getInstance();
        //得到一周的点赞量
        for (int i = 1;i<= 30;i++){
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String lastDay = formatter.format(calendar.getTime());
            String start = "2021-01-01 00:00:00";
            String end = lastDay + " 23:59:59";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            QueryWrapper<Follow> wrapper = new QueryWrapper<>();
            try {
                wrapper.between("gmt_create", sdf.format(sdf.parse(start)), sdf.format(sdf.parse(end)));
                wrapper.eq("followed_user_id", userId);
            } catch (ParseException e) {
                log.error(e.toString());
            }
            map.put(lastDay, Long.valueOf(baseMapper.selectCount(wrapper)));
        }
        result.setResult(map);
        return result;
    }

    @Override
    public Result<Integer> getTotalFanCount(String userId) {
        Result<Integer> result = new Result<>();
        QueryWrapper<Follow> wrapper = new QueryWrapper<>();
        wrapper.eq("followed_user_id", userId);
        result.setResult(baseMapper.selectCount(wrapper));
        return result;
    }

}
